package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	//router := gin.Default()
	//router.GET("/ping", func(c *gin.Context) {
	//	c.JSON(200, gin.H{
	//		"message": "你好 暖萍",
	//	})
	//})
	//router.Run() // 默认监听 0.0.0.0:8080

	router := gin.Default()

	router.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "欢迎访问首页",
		})
	})

	router.GET("/ping", func(c *gin.Context) {
		fmt.Println("完整路径：", c.FullPath())
		c.JSON(http.StatusOK, gin.H{
			"message": "pong222",
		})
	})

	router.Handle("GET", "helloGet", func(c *gin.Context) {
		path := c.FullPath()
		fmt.Println(path)
		c.JSON(http.StatusOK, gin.H{})
	})

	// 解析 http://localhost:8000/formStudent?name=123 请求
	router.GET("/formStudent", func(c *gin.Context) {
		path := c.FullPath()
		fmt.Println(path)

		var student Student
		err := c.ShouldBindQuery(&student)
		if err != nil {
			log.Fatal("访问失败", err.Error())
			return
		}
		fmt.Println(student.Name)
		fmt.Println(student.Classes)

		c.Writer.Write([]byte("student:" + student.Name))

	})

	// 注册 post body form方式
	router.POST("registerForm", func(c *gin.Context) {
		path := c.FullPath()
		fmt.Println(path)

		var user User
		err := c.ShouldBind(&user)
		if err != nil {
			log.Fatal("注册失败", err.Error())
			return
		}
		fmt.Println(user.Username)
		fmt.Println(user.Password)
		fmt.Println(user.Age)

		c.JSON(http.StatusOK, gin.H{
			"message": "ok",
		})
	})

	// 注册 post body json 方式
	router.POST("registerJson", func(c *gin.Context) {
		path := c.FullPath()
		fmt.Println(path)

		var user User
		err := c.BindJSON(&user)
		if err != nil {
			log.Fatal("注册失败", err.Error())
			return
		}
		fmt.Println(user.Username)
		fmt.Println(user.Password)
		fmt.Println(user.Age)

		c.JSON(http.StatusOK, gin.H{
			"message": "ok",
		})
	})

	router.Run(":8000")
	//router.Run("0.0.0.0:8000")
}

type Student struct {
	Name    string `form:"name" json:"name" binding:"required"`
	Classes string `form:"classes" json:"classes" binding:"required"`
}

type User struct {
	Username string `form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
	Age      int    `form:"age" json:"age" binding:"required"`
}
